package com.efounder.email.dao;

import java.util.ArrayList;
import java.util.Arrays;

import android.R.integer;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.efounder.email.contacts.SortModel;
import com.efounder.email.db.DBManager;
import com.efounder.email.db.EmailsDbHelper;
import com.efounder.email.model.Email;
import com.efounder.email.util.AbStrUtil;

/**
 * 邮件数据库操作
 * 
 * @author yqs
 * 
 */

public class OutboxEmailsDAO {

	private EmailsDbHelper emailsDbHelper;
	private SQLiteDatabase db;// 创建SQLiteDatabase对象

	public OutboxEmailsDAO(Context context) {
		emailsDbHelper = DBManager.getEmailsDbHelper(context);// 初始化DBgetOpenHelper对象
	}

	/**
	 * 保存邮件
	 * 
	 * @param email
	 */

	public void saveSingleEmail(Email email) {
		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		if (isExist(email.getMessageID())) {
			return;
		} else {
			db.execSQL(
					"insert into outboxemails(_id,receiver,ishavefile,subject,sendtime,image,userid,type)  values (?,?,?,?,?,?,?,?)",

					new Object[] { email.getMessageID(), email.getTo(),
							email.getIsHaveFile().toString(), email.getSubject(),
							email.getSentdata(), email.getImage(),email.getUserId(),email.getEmailType() });

		}
	}

	/**
	 * 保存邮件（集合）
	 * 
	 * @param ArrayList
	 *            <Email> emails 邮件list集合
	 */

	public void saveSetEmail(ArrayList<Email> emails) {
		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		Email email = new Email();
		for (int i = 0; i < emails.size(); i++) {
			email = emails.get(i);
			if (isExist(email.getMessageID())) {
				continue;
			} else {
				db.execSQL("insert into outboxemails(_id,receiver,ishavefile,subject,sendtime,image,userid,type)  values (?,?,?,?,?,?,?,?)",
						new Object[] { email.getMessageID(), email.getTo(),
						email.getIsHaveFile().toString(), email.getSubject(),
						email.getSentdata(), email.getImage(),email.getUserId(),email.getEmailType() });

			}
		}

	}

	/**
	 * 查找邮件
	 * 
	 * @return
	 */

	public ArrayList<Email> queryEmails(String type, String userId) {
		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		// 查找并存储到Cursor类中
		Cursor cursor = db.rawQuery("select * from outboxemails where type = ? and userid = ?", new String[] { type, userId });
		ArrayList<Email> allList = new ArrayList<Email>();
		// 遍历查询数据库
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);

			Email email = new Email();
			email.setMessageID(cursor.getString(cursor.getColumnIndex("_id")));
			email.setSubject(cursor.getString(cursor.getColumnIndex("subject")));
			email.setSentdata(cursor.getString(cursor
					.getColumnIndex("sendtime")));
			email.setTo(AbStrUtil.getNameFromEmail(cursor.getString(cursor.getColumnIndex("receiver"))));
			email.setImage(cursor.getInt(cursor.getColumnIndex("image")));
			email.setIsHaveFile((cursor.getString(cursor
					.getColumnIndex("ishavefile"))).equals("true") ? true
					: false);
			email.setIsRead(true);
			email.setEmailType(cursor.getString(cursor.getColumnIndex("type")));
			email.setUserId(cursor.getString(cursor.getColumnIndex("userid")));

			allList.add(email);
		}
		System.out.println("allList.size()：" + allList.size());
		return allList;
	}

	/**
	 * 获取邮件的数量
	 * 
	 * @return
	 */
	public long getEmailCount() {
		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		Cursor cursor = db.rawQuery("select count(_id) from outboxemails",
				null);// 获取id的记录数
		if (cursor.moveToNext())// 判断Cursor中是否有数据
		{
			return cursor.getLong(0);// 返回总记录数
		}
		return 0;

	}
	
	/**
	 * 获取邮件的数量
	 * 
	 * @return
	 */
	public long getEmailTypeCount(String type, String userId) {
		System.out.println(type + userId);
		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		Cursor cursor = db.rawQuery("select count(_id) from outboxemails where type =? and userid = ?",
				new String[] { type, userId });// 获取id的记录数
		if (cursor.moveToNext())// 判断Cursor中是否有数据
		{
			return cursor.getLong(0);// 返回总记录数
		}
		return 0;

	}

	/**
	 * 根据id查找邮件
	 * 
	 * @return
	 */

	public Email queryEmailById(String id) {
		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		// 查找并存储到Cursor类中
		Cursor cursor = db.rawQuery("select * from outboxemails where _id = ?",
				new String[] { id });
		if (cursor.moveToNext()) {
			Email email = new Email();
			email.setMessageID(cursor.getString(cursor.getColumnIndex("_id")));
			email.setTo(cursor.getString(cursor.getColumnIndex("receiver")));
			email.setSubject(cursor.getString(cursor.getColumnIndex("subject")));
			email.setSentdata(cursor.getString(cursor
					.getColumnIndex("sendtime")));
			email.setImage(cursor.getInt(cursor.getColumnIndex("image")));
			email.setIsHaveFile((cursor.getString(cursor
					.getColumnIndex("ishavefile"))).equals("true") ? true
					: false);
			//email.setIsHaveFile(false);
			email.setIsRead(true);
			email.setCopyTo(cursor.getString(cursor.getColumnIndex("chaosong")));
			email.setSecretTo(cursor.getString(cursor.getColumnIndex("misong")));
			email.setFrom(cursor.getString(cursor.getColumnIndex("sender")));
			email.setContent(cursor.getString(cursor.getColumnIndex("content")));

			// System.out.println(sortModel.name);
			return email;
		}

		return null;
	}

	/**
	 * 根据id查找邮件是否存在
	 * 
	 * @return
	 */

	public Boolean isExist(String id) {
		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		// 查找并存储到Cursor类中
		Cursor cursor = db.rawQuery("select * from outboxemails where _id = ?",
				new String[] { id });
		if (cursor.moveToNext()) {

			String itemId = cursor.getString(cursor.getColumnIndex("_id"));

			if (itemId != null && !itemId.equals("")) {
				return true;
			}

		}

		return false;
	}
	
	

	/**
	 * 更新邮件
	 * 
	 * @param
	 */
	public void updateEmail(Email email) {
		db = emailsDbHelper.getWritableDatabase();
		if (isExist(email.getMessageID())) {
			db.execSQL(
					"update  outboxemails  set sender=?,chaosong=?,misong =?,receiver = ?,content =?  where _id = ?",
					new Object[] { email.getFrom(), email.getCopyTo(),
							email.getSecretTo(), email.getTo(),
							email.getContent(), email.getMessageID()

					});

		} else {
			System.out.println("更新失败！邮件不存在");
		}
	}


	/**
	 * 删除邮件
	 * 
	 * @param ids
	 */
	public void deleteEmail(Integer... ids) {
		if (ids.length > 0)// 判断是否存在要删除的id
		{
			StringBuffer sb = new StringBuffer();// 创建StringBuffer对象
			for (int i = 0; i < ids.length; i++)// 遍历要删除的id集合
			{
				sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中
			}
			sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
			db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
			// 执行删除联系人操作
			db.execSQL("delete from outboxemails where _id in (" + sb + ")",
					(Object[]) ids);
		}

	}

	/**
	 * 删除邮件单个
	 * 
	 * @param ids
	 */
	public void deleteEmailById(String id) {

		db = emailsDbHelper.getWritableDatabase();// 初始化SQLiteDatabase对象
		// 执行删除联系人操作
		db.execSQL("delete from outboxemails where _id = ?",
				new String[] { id });

	}

	/**
	 * 清除全部数据
	 */
	public void deleteTableData() {
		db = emailsDbHelper.getWritableDatabase();
		db.execSQL("delete from outboxemails");
	}
	
	/**
	 * 通过邮件类型删除表中数据
	 * @param type
	 */
	public void deleteDataByType(String type) {
		db = emailsDbHelper.getWritableDatabase();
		db.execSQL("delete from outboxemails where type =?",new String[] { type });
	}
}
